<template>
  <el-card class="production-order-card">
    <!-- Header Section -->
    <template #header>
      <div class="card-header">
        <span>生产工单数据</span>
      </div>
    </template>

    <!-- Filter and Action Bar -->
    <div class="filter-bar">
      <!-- (Unchanged from previous version) -->
      <div class="left-actions">
        <el-input
          v-model="searchParams.keyword"
          placeholder="请输入编号..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prepend>
            <el-select v-model="searchParams.type" style="width: 130px">
              <el-option label="销售订单编号" value="salesOrderNo" />
              <el-option label="客户PO" value="customerPO" />
              <el-option label="品号" value="partNo" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        <el-button type="success" @click="handleSyncData">同步数据</el-button>
        <span class="sync-time-label">最近同步时间: {{ lastSyncTime }}</span>
      </div>
      <div class="right-actions">
        <el-button @click="handleClearFilters">清空全部条件</el-button>
        <el-button @click="handleAdvancedFilter">高级筛选</el-button>
      </div>
    </div>

    <!-- Main Content: Nested Table with On-Demand Loading -->
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        @expand-change="handleExpandChange"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="expand" width="55" align="center">
          <template #default="props">
            <div class="expanded-content" v-loading="props.row.productionOrdersLoading">
              <el-table
                v-if="props.row.productionOrders?.length"
                :data="props.row.productionOrders"
                border
              >
                <el-table-column prop="workOrderNo" label="工单号" sortable />
                <el-table-column prop="itemCode" label="品号" sortable />
                <el-table-column prop="productType" label="产品类型" sortable />
                <el-table-column prop="unit" label="单位" width="80" align="center" />
                <el-table-column prop="wipCompletedQty" label="在制品完成数量" align="center" />
                <el-table-column prop="wipScrappedQty" label="在制品报废数量" align="center" />
                <el-table-column prop="defectiveQty" label="不良数量" align="center" />
                <el-table-column prop="reworkQty" label="返工数量" align="center" />
              </el-table>
              <el-empty
                v-else-if="!props.row.productionOrdersLoading"
                description="该销售订单下无生产工单"
                :image-size="80"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="saleOrderCode" label="销售订单编号" width="180" />
        <el-table-column prop="customerCode" label="客户PO" />
        <el-table-column prop="source" label="单据来源" />
        <el-table-column prop="factoryName" label="工厂" />
        <el-table-column prop="orderStatus" label="⼯单状态" />
        <el-table-column prop="" label="品号" />
        <el-table-column prop="" label="单位" width="80" align="center" />
        <el-table-column prop="" label="入库数量" align="center" />
        <el-table-column prop="" label="预计产量" align="center" />
        <el-table-column prop="deliveryDate" label="客户交期" />
        <el-table-column prop="completeDate" label="批准日期" />
        <el-table-column prop="shipmentDate" label="出货日期" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <!-- 步骤 2: 用户点击这个按钮 -->
            <el-button type="primary" link @click="handleViewDetails(scope.row)">
              查看工单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Pagination -->
    <div class="pagination-container" v-if="pagination.total > 0">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="sizes, prev, pager, next, jumper,->, slot"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <!-- Floating Info Button -->
        <div class="footer-status-bar">
          <el-tag class="product-count-tag" size="large">
            生产报工数 {{ pagination.total }}
          </el-tag>
          <el-button :icon="MoreFilled" circle />
        </div>
      </el-pagination>
      <!-- <el-dialog -->
      <el-drawer
        v-model="dialogVisible"
        :title="`生产工单数据明细 - ${currentOrderNumber}`"
        size="89.6%"
        direction="rtl"
        :close-on-click-modal="false"
        :show-close="false"
        :modal="false"
        style="margin-top: 53px"
      >
        <template #header="{ titleId }">
          <div style="display: flex; color: black" @click="handleBackToList">
            <el-icon size="26" style="margin-right: 10px"><Back /></el-icon>
            <h3 :id="titleId">返回列表</h3>
          </div>
        </template>
        <!-- 对话框的内容 -->
        <ProductionOrderDetails
          v-if="dialogVisible"
          :sales-order-number="currentOrderNumber"
          viewMode="reporting"
        />
        <!-- </el-dialog> -->
      </el-drawer>
    </div>
    <!-- 高级筛选 -->
    <el-dialog v-model="visibleFiterDialog" width="380" :show-close="false">
     <advancedFilter ref="advancedFilter"/>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visibleFiterDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmFilter">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, MoreFilled, Back } from '@element-plus/icons-vue'
import { OrderApi, OrderVO, ProductOrderVO } from '@/api/order/index'
import { ProductionWorkOrderApi } from '@/api/productionworkorder/index'
import ProductionOrderDetails from '@/components/ProductionOrderDetails.vue'
import advancedFilter from './advancedFilter.vue'
import {currentTime} from '@/utils/currentTime'
// 关于高级筛选
const visibleFiterDialog = ref(false)
const lastSyncTime = ref('2025/06/06 20:00:00')

const syncData = () => {
  lastSyncTime.value = currentTime()
}
const confirmFilter = () => { 
  console.log('confirmFilter');
  visibleFiterDialog.value = false
  
}
interface ProductionOrderDetail {
  workOrderNo: string
  partNo: string
  productType: string
  unit: string
  wipCompleted: number
  wipScrapped: number
  defective: number
  rework: number
}

const dialogVisible = ref(false)
const currentOrderNumber = ref('')
const handleBackToList = () => {
  dialogVisible.value = false
}
const searchParams = reactive({
  type: 'salesOrderNo',
  keyword: ''
})
const tableData = ref<OrderVO[]>([])
const loading = ref(false)
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const fetchData = async () => {
  loading.value = true
  try {
    // 构造接口参数（与OrderApi.getOrderPage要求的参数格式匹配）
    const params = {
      pageNo: pagination.currentPage, // 当前页码
      pageSize: pagination.pageSize, // 每页数量
      searchType: searchParams.type, // 搜索类型（对应接口参数名可能需要调整）
      keyword: searchParams.keyword // 搜索关键词
    }

    // 调用真实接口
    const response = await OrderApi.getOrderPage(params)

    tableData.value = response.list
    pagination.total = response.total
  } catch (error) {
    console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单数据失败，请重试')
  } finally {
    loading.value = false
  }
}

const fetchProductionOrders = async (salesOrderNo: string): Promise<ProductionOrderDetail[]> => {
  try {
    // 调用生产工单API的getList接口（根据实际接口参数调整）
    const response = await ProductionWorkOrderApi.getList({
      salesOrderNo: salesOrderNo // 通过销售订单号筛选关联工单
    })

    // 假设接口返回格式：{ list: 生产工单数组 }
    return response || []
  } catch (error) {
    console.error('获取生产工单失败:', error)
    ElMessage.error('获取生产工单详情失败')
    return []
  }
}

const handleExpandChange = async (row: ProductOrderVO, expandedRows: ProductOrderVO[]) => {
  const isExpanding = expandedRows.some((r) => r.id === row.id)

  // 仅在展开且数据未加载时触发
  if (isExpanding && !row.productionOrders) {
    row.productionOrdersLoading = true // 显示加载状态
    try {
      // 从当前行获取销售订单号（根据实际字段名调整，假设字段为saleOrderCode）
      const salesOrderNo = row.saleOrderCode
      if (!salesOrderNo) {
        ElMessage.warning('销售订单号缺失，无法获取生产工单')
        return
      }

      // 点击展开时调用真实接口
      const data = await fetchProductionOrders(salesOrderNo)
      row.productionOrders = data
    } finally {
      row.productionOrdersLoading = false // 隐藏加载状态
    }
  }
}

const handleViewDetails = (row: { saleOrderCode: string }) => {
  // 1. 记录要查看的订单号
  currentOrderNumber.value = row.saleOrderCode
  // 2. 将开关设为 true，el-dialog 就会自动弹出
  dialogVisible.value = true
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}
const handleSyncData = () => {
  ElMessage.info('正在同步数据...')
  fetchData()
}
const handleClearFilters = () => {
  searchParams.keyword = ''
  searchParams.type = 'salesOrderNo'
  pagination.currentPage = 1
  fetchData()
  ElMessage.success('已清空所有筛选条件')
}
const handleAdvancedFilter = () => {
  // ElMessageBox.alert('此功能将打开一个包含更多筛选选项的对话框。', '高级筛选', {
  //   confirmButtonText: '好的'
  // })
  visibleFiterDialog.value = true
}
const handleSizeChange = (newSize: number) => {
  pagination.pageSize = newSize
  fetchData()
}
const handleCurrentChange = (newPage: number) => {
  pagination.currentPage = newPage
  fetchData()
}

onMounted(() => {
  fetchData()
  syncData()
})
</script>

<style scoped>
.production-order-card {
  position: relative;
  min-height: 700px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 450px;
}

.el-table {
  overflow: visible;
}

.el-table .el-table__header-wrapper th .cell {
  overflow: visible;
}

.expanded-content {
  min-height: 100px; /* Ensure loading spinner has space */
  padding: 15px 20px 15px 55px; /* Indent to align with main table content */
  background-color: #fafafa;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.floating-info {
  position: absolute;
  right: 20px;
  bottom: 20px;
  z-index: 10;
  display: flex;
  padding: 8px 15px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  background-color: #67c23a;
  border-radius: 20px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
  transition: all 0.3s ease;
  align-items: center;
  gap: 8px;
}

.floating-info:hover {
  background-color: #85ce61;
  transform: translateY(-2px);
}

.floating-info .count {
  display: inline-flex;
  height: 24px;
  min-width: 24px;
  padding: 0 4px;
  font-size: 16px;
  font-weight: bold;
  background-color: rgb(255 255 255 / 20%);
  border-radius: 12px;
  justify-content: center;
  align-items: center;
}

.footer-status-bar {
  display: flex;
  padding: 15px 20px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  justify-content: flex-end;
  align-items: center;
}

/* 覆盖 el-button 的默认样式使其与 tag 协调 */
.footer-status-bar .el-button {
  border-color: #dcdfe6;
}

.product-count-tag {
  height: 32px;
  padding: 0 15px;
  font-size: 14px;
  color: white;
  background-color: #95d475;
  border: none;
}
:deep(.el-card.is-always-shadow) {
  box-shadow: none;
}
:deep(.el-drawer) {
  box-shadow: none;
}
</style>